{{define "users"}}
{{template "header" .}}

<div class="container">
  <h2>Users</h2>
  <form>
    <fieldset>
      <legend>Authorize New User</legend>
      <label>Email</label>
      <input type="text" class="input-xlarge" id="new-user-email" placeholder="ycoppel@google.com"></input>
      <div>
        <button type="submit" class="btn" onclick="newUser(); return false;">Add</button>
      </div>
    </fieldset>
  </form>

  <h3>List</h3>
  <table id="user-table" class="table table-striped table-hover table-condensed">
    <thead>
      <tr>
        <th>User</th>
        <th>Actions</th>
      </tr>
    </thead>
    <tbody id="user-tbody"></tbody>
  </table>

  <div id="command"></div>
</div>

<script src="/static/api.js"></script>
<script>
function newUser() {
  var email = document.getElementById('new-user-email').value;
  console.log(email);

  $.ajax({
    url: "/api/user/new",
    data: {'email': email},
  	dataType: 'json',
  	success: function(d) {
      setTimeout(refreshUsersTable, 100);
    },
    error: function(d) {
      console.log(d);
      alert(d.responseText);
    }
  });
}

function refreshUsersTable() {
  listUsers(
  	function(d) {
      console.log(d);
      var tb = document.createElement('tbody');
      tb.id='user-tbody';
      for (var i = 0; i < d.Users.length; ++i) {
        var userData = d.Users[i];
        var tr = document.createElement('tr');

        var td = document.createElement('td');
        td.textContent = userData.Email
        tr.appendChild(td);

        var td = document.createElement('td');
        td.textContent = 'Delete';
        tr.appendChild(td);

        tb.appendChild(tr);
      }
      var table = document.getElementById('user-table');
      table.replaceChild(
        tb,
        document.getElementById('user-tbody'));
    },
    function(d) {
      console.log(d);
      alert(d.responseText);
    }
  );
}

refreshUsersTable();
</script>

{{template "footer"}}
{{end}}
